package com.selfdriving.map;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.mapapi.map.RouteOverlay;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPlanNode;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKRoute;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKShareUrlResult;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.selfdriving.BaseApplication;
import com.selfdriving.R;
import com.selfdriving.utils.BMapUtil;
import com.selfdriving.utils.LogUtil;

/** 地图 **/
public class ScenicLocitonMap
{
	// 定位相关
	private LocationData locData = null;
	private MyLocationListenner myListener;
	private locationOverlay myLocationOverlay = null;// 定位图层
	private Button requestLocButton = null;// UI相关
	MapView mMapView = null; // 地图View
	private MapController mMapController = null;
	// 搜索相关
	private MKSearch mSearch = null;
	private RouteOverlay routeOverlay = null;
	private MKRoute route = null;// 保存驾车/步行路线数据的变量，供浏览节点时使用
	// 浏览路线节点相关
	private Button mBtnPre = null;// 上一个节点
	private Button mBtnNext = null;// 下一个节点
	private int nodeIndex = -2;// 节点索引,供浏览节点时使用
	private Context context;
	private GeoPoint mypoint = null;
	public BaseApplication mApplication;
	private TextView popupText = null;// 泡泡view
	private PopupOverlay pop = null;// 弹出泡泡图层，浏览节点时使用
	private View viewCache = null;
	private List<String> stepData = null;
	ListView listView;
	GeoPoint geoPointpoint = null;
	String keyWord;
	private TextView title;// 头部显示的文字
	ProgressDialog dialog;// 正在加载的对话框
	boolean isLoading = true;// 是否正在加载中...
	boolean isShow = true;// 是否需要显示问下提示
	int x = 0;// 加载数次

	public ScenicLocitonMap(BaseApplication mApplication, Context context,
			MapView mapView, String keyWord)
	{
		this.mApplication = mApplication;
		this.context = context;
		this.mMapView = mapView;
		this.keyWord = keyWord;
		myListener = new MyLocationListenner();
		mMapView.getController().setZoom(14);
		mMapView.getController().enableClick(true);
		mMapController = mMapView.getController();
		map();
	}

	public ScenicLocitonMap(BaseApplication mApplication, Context context,
			Button requestLocButton, MapView mapView, List<String> stepData,
			ListView listView, GeoPoint point, TextView title,
			ProgressDialog dialog)
	{
		// TODO Auto-generated constructor stub
		isLoading = true;
		isShow = true;
		myListener = new MyLocationListenner();
		this.mApplication = mApplication;
		this.context = context;
		this.dialog = dialog;
		this.stepData = stepData;
		this.title = title;
		this.requestLocButton = requestLocButton;
		this.listView = listView;
		this.geoPointpoint = point;
		mMapView = mapView;
		mMapController = mMapView.getController();
		mMapController.setZoom(14);
		mMapController.enableClick(true);
		mMapController.setCenter(mApplication.myPoint);
		listView.setOnItemClickListener(new StepListOnItem());
		initscenic();
		new LoadingMap().start();
	}

	public class LoadingMap extends Thread
	{
		@Override
		public void run()
		{
			while (isLoading)
			{
				try
				{
					Thread.sleep(2000);
				} catch (InterruptedException e)
				{
				}
				mApplication.mLocClient.requestLocation();
				mApplication.mLocClient.start();
				System.out.println("------------");
				x++;
				if (x > 5)
				{
					hand.sendEmptyMessage(0);
					isLoading = false;
				}
			}
			super.run();
		}
	}

	Handler hand = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			// TODO Auto-generated method stub
			switch (msg.what)
			{
			case 0:
				if (dialog.isShowing())
				{
					dialog.dismiss();
				}
				break;
			}
			super.handleMessage(msg);
		}
	};

	/**
	 * 初始化景点定位各控件，搜索路线功能实现。
	 */
	public void initscenic()
	{
		map();
		// 创建 弹出泡泡图层
		createPaopao();
		mBtnPre = (Button) ((Activity) context).findViewById(R.id.pre);
		mBtnNext = (Button) ((Activity) context).findViewById(R.id.next);
		mBtnPre.getBackground().setAlpha(70);
		mBtnNext.getBackground().setAlpha(70);
		mBtnPre.setOnClickListener(nodeClickListener);
		mBtnNext.setOnClickListener(nodeClickListener);

		// 修改定位数据后刷新图层生效
		mMapView.refresh();

	}

	/**
	 * 手动定位按钮监听器
	 */
	OnClickListener nodeClickListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			// 浏览路线节点
			nodeClick(v);
		}
	};

	/**
	 * 初始化地图控件
	 */
	public void map()
	{
		// 定位初始化
		locData = new LocationData();
		mApplication.mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setAddrType("all");// all时，表示返回地址信息。
		option.disableCache(true);// 禁用缓存定位
		option.setPoiExtraInfo(true); // 是否需要POI的电话和地址等详细信息
		mApplication.mLocClient.setLocOption(option);
		mApplication.mLocClient.start();
		mSearch = new MKSearch();
		mSearch.init(mApplication.mBMapManager, new MyMKSearchListener());
		OnClickListener btnClickListener = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				// 清除其他图层
				requestLocClick();// 手动定位请求
			}
		};
		if (requestLocButton != null)
		{
			requestLocButton.setOnClickListener(btnClickListener);
		}
		// 定位图层初始化
		myLocationOverlay = new locationOverlay(mMapView);
		// 设置定位数据
		myLocationOverlay.setData(locData);
		// 添加定位图层
		mMapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();
	}

	/**
	 * 节点浏览
	 * 
	 * @param v
	 */
	public void nodeClick(View v)
	{
		// 驾车、步行使用的数据结构相同，因此类型为驾车或步行，节点浏览方法相同
		if (nodeIndex < -1 || route == null || nodeIndex >= route.getNumSteps())
			return;

		// 上一个节点
		if (mBtnPre.equals(v) && nodeIndex > 0)
		{
			// 索引减
			nodeIndex--;
			setSelect();
		}
		// 下一个节点
		if (mBtnNext.equals(v) && nodeIndex < (route.getNumSteps() - 1))
		{
			// 索引加
			nodeIndex++;
			setSelect();
		}
	}

	private class StepListOnItem implements OnItemClickListener
	{
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id)
		{
			// TODO Auto-generated method stub
			// 移动到指定索引的坐标
			mMapView.getController().animateTo(
					route.getStep(position).getPoint());
			// 弹出泡泡
			popupText.setBackgroundResource(R.drawable.popup);
			popupText.setText(route.getStep(position).getContent());
			pop.showPopup(BMapUtil.getBitmapFromView(popupText),
					route.getStep(position).getPoint(), 5);
			ScenicLocation.stepList.setSelection(position);
		}
	}

	public void setSelect()
	{
		// 移动到指定索引的坐标
		mMapView.getController().animateTo(route.getStep(nodeIndex).getPoint());
		// 弹出泡泡
		popupText.setBackgroundResource(R.drawable.popup);
		popupText.setText(route.getStep(nodeIndex).getContent());
		pop.showPopup(BMapUtil.getBitmapFromView(popupText),
				route.getStep(nodeIndex).getPoint(), 5);
		if (ScenicLocation.stepList != null
				&& ScenicLocation.stepList.getChildCount() > 0)
		{
			ScenicLocation.stepList.setSelection(nodeIndex);
		}
	}

	/**
	 * 手动触发一次定位请求
	 */
	public void requestLocClick()
	{
		mApplication.mLocClient.requestLocation();
		mApplication.mLocClient.start();
		isShow = true;
		LogUtil.showCustomToast(context, "正在定位……");
	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener
	{
		@Override
		public void onReceiveLocation(BDLocation location)
		{
			if (location == null)
			{
				LogUtil.showCustomToast(context, "无法获得查询信息");
				return;
			}
			if (isShow && location != null && !location.getAddrStr().equals(""))
			{
				isShow = false;
				LogUtil.showCustomToast(context, location.getAddrStr());
			}
			double longitude = location.getLongitude();// 经度
			double Latitude = location.getLatitude();// 纬度
			mypoint = new GeoPoint((int) (Latitude * 1e6),
					(int) (longitude * 1e6));
			// 更新定位数据并移动到定位位置
			locData.latitude = location.getLatitude();
			locData.longitude = location.getLongitude();
			// 如果不显示定位精度圈，将accuracy赋值为0即可
			locData.accuracy = location.getRadius();
			locData.direction = location.getDerect();
			myLocationOverlay.setData(locData);
			// 更新图层数据执行刷新后生效
			mMapView.refresh();
			GeoPoint point = new GeoPoint((int) (locData.latitude * 1e6),
					(int) (locData.longitude * 1e6));
			GeoPoint endpoint = null;
			if (geoPointpoint != null)
			{
				endpoint = geoPointpoint;
				MKPlanNode start = new MKPlanNode();
				start.pt = mypoint;
				MKPlanNode end = new MKPlanNode();
				end.pt = endpoint;
				mSearch.drivingSearch("南昌", start, "南昌", end);// 路线搜索
				// 移动地图到定位点
				try
				{
					mMapController.animateTo(point);
				} catch (Exception e)
				{
					System.out.println("*-**-*-**-***-*-**-*");
				}
				GeoPoint p1LL = mypoint;// 我当前位置的经纬度
				GeoPoint p2LL = end.pt;// 景点所在位置的经纬度
				// 经纬度计算。算当前位置距离景点的距离，返回米/1000 =公里
				double distance = DistanceUtil.getDistance(p1LL, p2LL) / 1000;
				String dis = String.format("%.2f", distance);
				title.setText("约" + dis + "km");
			}
			if (keyWord != null)
			{
				mSearch.poiSearchNearBy(keyWord, mypoint, 5000);
			}
		}

		public void onReceivePoi(BDLocation poiLocation)
		{
			if (poiLocation == null)
			{
				return;
			}
		}
	}

	/**
	 * 创建弹出泡泡图层
	 */
	public void createPaopao()
	{

		// 泡泡点击响应回调
		PopupClickListener popListener = new PopupClickListener()
		{
			@Override
			public void onClickedPopup(int index)
			{
				Log.v("click", "clickapoapo");
			}
		};
		pop = new PopupOverlay(mMapView, popListener);
	}

	/**
	 * 各搜索功能监听器
	 * 
	 * @author Administrator
	 */
	public class MyMKSearchListener implements MKSearchListener
	{

		@Override
		public void onGetAddrResult(MKAddrInfo res, int error)
		{
			// TODO Auto-generated method stub
		}

		@Override
		public void onGetBusDetailResult(MKBusLineResult arg0, int arg1)
		{
			// TODO Auto-generated method stub

		}

		@Override
		public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error)
		{// 驾车路线搜索
			// TODO Auto-generated method stub
			// 错误号可参考MKEvent中的定义
			if (error != 0 || res == null)
			{
				LogUtil.showCustomToast(context, "抱歉，未找到结果");
				return;
			}
			try
			{

				routeOverlay = new RouteOverlay((Activity) context, mMapView);
				// 此处仅展示一个方案作为示例
				routeOverlay.setData(res.getPlan(0).getRoute(0));
				// 添加路线图层
				mMapView.getOverlays().add(routeOverlay);
				// 执行刷新使生效
				mMapView.refresh();
				// 使用zoomToSpan()绽放地图，使路线能完全显示在地图上
				mMapView.getController().zoomToSpan(
						routeOverlay.getLatSpanE6(),
						routeOverlay.getLonSpanE6());
				// 移动地图到起点
				mMapView.getController().animateTo(res.getStart().pt);
				// 将路线数据保存给全局变量
				route = res.getPlan(0).getRoute(0);
				// 重置路线节点索引，节点浏览时使用
				if (!stepData.isEmpty())
				{
					stepData.removeAll(stepData);
					showList();
				} else
				{
					showList();
				}
				nodeIndex = -1;
				viewCache = LayoutInflater.from(context).inflate(
						R.layout.custom_text_view, null);
				popupText = (TextView) viewCache.findViewById(R.id.textcache);
				if (dialog.isShowing())
				{
					isLoading = false;
					dialog.dismiss();
				}
			} catch (Exception e)
			{
				System.out.println("666665565");
			}
		}

		@Override
		public void onGetPoiDetailSearchResult(int arg0, int arg1)
		{
			// TODO Auto-generated method stub

		}

		@Override
		public void onGetPoiResult(MKPoiResult res, int type, int error)
		{

		}

		@Override
		public void onGetShareUrlResult(MKShareUrlResult arg0, int arg1,
				int arg2)
		{
			// TODO Auto-generated method stub
		}

		@Override
		public void onGetSuggestionResult(MKSuggestionResult res, int arg1)
		{
			// TODO Auto-generated method stub

		}

		@Override
		public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1)
		{
			// TODO Auto-generated method stub
		}

		@Override
		public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1)
		{
			// TODO Auto-generated method stub
		}
	}

	/**
	 * 添加listView 数据
	 */
	private void showList()
	{
		int x = 0;
		while (x >= 0)
		{
			if (route.getStep(x) != null)
			{
				stepData.add(route.getStep(x).getContent());
				x++;
			} else
			{
				x = -1;
			}
		}
		if (ScenicLocation.adapter != null)
		{
			ScenicLocation.adapter.notifyDataSetChanged();
		}
	}

	// 继承MyLocationOverlay重写dispatchTap实现点击处理
	public class locationOverlay extends MyLocationOverlay
	{

		public locationOverlay(MapView mapView)
		{
			super(mapView);
			// TODO Auto-generated constructor stub
		}
	}
}